package com.activity.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.activity.App;
import com.activity.BriefActivity;
import com.activity.CategoryActivity;
import com.activity.CategoryListActivity;
import com.activity.ImageActivity;
import com.activity.PersonInfoActivity;
import com.activity.bean.CategoryBean;
import com.activity.bean.OpusBean;
import com.activity.bean.UserBean;
import com.baoyz.actionsheet.ActionSheet;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ImageViewUtil;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.example.lzbase.BaseActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.shizhefei.view.largeimage.LargeImageView;
import com.shizhefei.view.largeimage.factory.InputStreamBitmapDecoderFactory;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.lujun.androidtagview.TagContainerLayout;
import co.lujun.androidtagview.TagView;

public class PersonAdapter1 extends GroupedRecyclerViewAdapter {
    public TagAdapter tagAdapter;


    public ArrayList<OpusBean> data = new ArrayList();

    public ArrayList<String> tag = new ArrayList<>();
    public ArrayList<CategoryBean> categorys = new ArrayList<>();


    public  boolean ishiden;
    public PersonAdapter1(Context context) {
        super(context);

    }


    @Override
    public boolean hasHeader(int groupPosition) {

        return true;
    }

    @Override
    public boolean hasFooter(int groupPosition) {
        return true;
//        return data.size() == 0 ? true : false;
    }

    @Override
    public int getGroupCount() {

        return 1;
    }


    @Override
    public int getChildrenCount(int groupPosition) {

        return data.size();

    }

    @Override
    public int getChildViewType(int groupPosition, int childPosition) {

        return TYPE_CHILD;
    }

    @Override
    public int getHeaderLayout(int viewType) {
        return R.layout.header_person1;
    }

    @Override
    public int getFooterLayout(int viewType) {
        return R.layout.item_empty_1;
    }

    @Override
    public int getChildLayout(int viewType) {


        return R.layout.item_personal_cell;
    }

    public personListener personListener;

    @Override
    public void onBindHeaderViewHolder(BaseViewHolder holder, int groupPosition) {
        PersonHeaderHolder personHeaderHolder = (PersonHeaderHolder) holder;

        personHeaderHolder.setData();

//        personHeaderHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                personHeaderHolder.btnDetail.setSelected(!personHeaderHolder.btnDetail.isSelected());
//                if (personHeaderHolder.btnDetail.isSelected()) {
//                    personHeaderHolder.tvBrief.setLines(3);
//                } else {
//                    personHeaderHolder.tvBrief.setLines(1);
//                }
//            }
//
//        });
        tagAdapter.setOnChildClickListener(new OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {


                if (childPosition == tag.size() - 1) {
                    Bundle param = new Bundle();
                    param.putBoolean("param", true);
                    param.putString("super", "0");
                    ActivityUtil.startActivity(mContext, CategoryActivity.class, param);
                } else {

                    Bundle param = new Bundle();
                    param.putString("name", categorys.get(childPosition).getWorkscategoryname());
                    param.putString("id", categorys.get(childPosition).getWorkscategoryid());
                    ActivityUtil.startActivity(mContext, CategoryListActivity.class, param);
                }

            }
        });
//        personHeaderHolder.tvName.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ActivityUtil.startActivity(mContext, PersonInfoActivity.class);
//            }
//        });
        personHeaderHolder.r_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtil.startActivity(mContext, PersonInfoActivity.class);
            }
        });
        personHeaderHolder.lIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActionSheet.createBuilder(mContext, ((BaseActivity) mContext).getSupportFragmentManager())
                        .setCancelButtonTitle(mContext.getString(R.string.cacel))
                        .setOtherButtonTitles(mContext.getString(R.string.camera), mContext.getString(R.string.take_photo))
                        .setCancelableOnTouchOutside(true)
                        .setListener(new ActionSheet.ActionSheetListener() {
                            @Override
                            public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                            }

                            @Override
                            public void onOtherButtonClick(ActionSheet actionSheet, int index) {

                                if (index == 0) {
                                    PictureSelector.create((Activity) mContext)
                                            .openCamera(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

                                            .maxSelectNum(1)// 最大图片选择数量 int
                                            .imageSpanCount(4)// 每行显示个数 int
                                            .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                            .previewImage(true)// 是否可预览图片 true or false
                                            .previewVideo(true)// 是否可预览视频 true or false
                                            .enablePreviewAudio(true) // 是否可播放音频 true or false
                                            .isCamera(true)// 是否显示拍照按钮 true or false
                                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                            .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                            .enableCrop(true)
                                            .showCropGrid(false)
                                            .withAspectRatio(1, 1)
                                            .compress(true)// 是否压缩 true or false
                                            .isGif(false)// 是否显示gif图片 true or false
                                            .openClickSound(false)// 是否开启点击声音 true or false
                                            .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                            .minimumCompressSize(100)// 小于100kb的图片不压缩
                                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                                } else {
                                    PictureSelector.create((Activity) mContext)
                                            .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

                                            .maxSelectNum(1)// 最大图片选择数量 int
                                            .imageSpanCount(4)// 每行显示个数 int
                                            .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                            .previewImage(true)// 是否可预览图片 true or false
                                            .previewVideo(true)// 是否可预览视频 true or false
                                            .enablePreviewAudio(true) // 是否可播放音频 true or false
                                            .isCamera(true)// 是否显示拍照按钮 true or false
                                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                            .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                            .enableCrop(true)
                                            .showCropGrid(false)
                                            .withAspectRatio(1, 1)
                                            .compress(true)// 是否压缩 true or false
                                            .isGif(false)// 是否显示gif图片 true or false
                                            .openClickSound(false)// 是否开启点击声音 true or false
                                            .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                            .minimumCompressSize(100)// 小于100kb的图片不压缩
                                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                                }
                            }
                        }).show();
            }
        });

        personHeaderHolder.tv_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtil.startActivity(mContext, BriefActivity.class);
            }
        });
        personHeaderHolder.l_yincnag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ishiden = !ishiden;
                if(ishiden){
                    personHeaderHolder.l_yincang_bg.setVisibility(View.GONE);
                }else {
                    personHeaderHolder.l_yincang_bg.setVisibility(View.VISIBLE);
                }
                if(ishiden){

                    personHeaderHolder.tvYincang.setText("显示全部个人信息");
                    personHeaderHolder.ivYincang.setImageResource(R.drawable.jiantou_xia);
                }else {
                    personHeaderHolder.tvYincang.setText("隐藏全部个人信息");
                    personHeaderHolder.ivYincang.setImageResource(R.drawable.jiantou_shang);
                }
            }
        });
        personHeaderHolder.tv_guan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("name", "官网");
                bundle.putString("image", "guanwang.png");
                bundle.putFloat("width", 750.0f);
                bundle.putFloat("height", 3696.0f);
                ActivityUtil.startActivity(mContext, ImageActivity.class, bundle);
            }
        });
        personHeaderHolder.tv_yuyue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("name", "我要预约");
                bundle.putString("image", "yuyue.png");
                bundle.putFloat("width", 750.0f);
                bundle.putFloat("height", 3000.0f);
                ActivityUtil.startActivity(mContext, ImageActivity.class, bundle);
            }
        });
        personHeaderHolder.tv_gengduo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Bundle bundle = new Bundle();
//                bundle.putString("name", "我的作品");
//                bundle.putString("image", "zuopin.png");
//                bundle.putFloat("width", 1242.0f);
//                bundle.putFloat("height", 3768.0f);
//                ActivityUtil.startActivity(mContext, ImageActivity.class, bundle);
            }
        });
        personHeaderHolder.tagcontainerLayout2.setOnTagClickListener(new TagView.OnTagClickListener() {
            @Override
            public void onTagClick(int position, String text) {

                if (position == tag.size() - 1) {
                    Bundle param = new Bundle();
                    param.putBoolean("param", true);
                    param.putString("super", "0");
                    ActivityUtil.startActivity(mContext, CategoryActivity.class, param);
                } else {

                    Bundle param = new Bundle();
                    param.putString("name", categorys.get(position).getWorkscategoryname());
                    param.putString("id", categorys.get(position).getWorkscategoryid());
                    ActivityUtil.startActivity(mContext, CategoryListActivity.class, param);
                }
            }

            @Override
            public void onTagLongClick(int position, String text) {

            }

            @Override
            public void onSelectedTagDrag(int position, String text) {

            }

            @Override
            public void onTagCrossClick(int position) {

            }
        });
    }

    @Override
    public void onBindFooterViewHolder(BaseViewHolder holder, int groupPosition) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.itemView.findViewById(R.id.iv_icon).getLayoutParams();
        Window window = ((Activity) mContext).getWindow();

        WindowManager.LayoutParams layoutParams = window.getAttributes();
        WindowManager m = ((Activity) mContext).getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        params.height = (int) (d.getWidth()*2275.0/750.0);
        holder.itemView.findViewById(R.id.iv_icon).setLayoutParams(params);
//        try {
//            ( (LargeImageView) holder.get(R.id.iv_icon)).setImage(new InputStreamBitmapDecoderFactory(mContext.getResources().getAssets().open("zuopin.png")) );
//        } catch (IOException e) {
//
//            Log.e("sdada",e.toString());
//            e.printStackTrace();
//
//
//        }
    }


    @Override
    public void onBindChildViewHolder(BaseViewHolder holder, int groupPosition, int childPosition) {


        ((PersonalHolder) holder).setData(data.get(childPosition));

        ((PersonalHolder) holder).iv_praise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (personListener != null) {
                    personListener.praiseClick(childPosition);
                }

            }
        });
    }

    //
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_CHILD) {


            View view = LayoutInflater.from(mContext).inflate(getChildLayout(viewType), parent, false);

            return new PersonalHolder(view);

        } else if (viewType == TYPE_HEADER) {
            View view = LayoutInflater.from(mContext).inflate(getHeaderLayout(viewType), parent, false);

            return new PersonHeaderHolder(view);
        } else
            return super.onCreateViewHolder(parent, viewType);
    }


    public class PersonalHolder extends BaseViewHolder {

        @BindView(R.id.iv_icon)
        ImageView ivIcon;
        @BindView(R.id.tv_content)
        TextView tvContent;
        @BindView(R.id.iv_user_icon)
        ImageView ivUserIcon;
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_num)
        TextView tvNum;
        @BindView(R.id.iv_dianzan)
        ImageView iv_praise;

        public PersonalHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(OpusBean data) {

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ivIcon.getLayoutParams();


            WindowManager m = ((Activity) mContext).getWindowManager();
            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
            params.width = (d.getWidth() - ScreenUtil.dp2px(mContext, 12)) / 2;
//            if (data.images().size() > 0) {
//                ImageViewUtil.loadImageCorner(data.images().get(0), ivIcon, mContext,R.drawable.meinv);
//            } else {
//                ivIcon.setImageResource(R.drawable.meinv);
//            }

            if (data.getWorkssizes() != null) {
                ArrayList<String> sizes = new ArrayList<String>(Arrays.asList(StringUtils.split(data.getWorkssizes(), "|")));

                if (sizes.size() > 0) {
                    ArrayList<String> size1 = new ArrayList<String>(Arrays.asList(StringUtils.split(sizes.get(0), ",")));
                    params.height = (int) (params.width * Float.valueOf(size1.get(1)) / Float.valueOf(size1.get(0)));
                    ivIcon.setLayoutParams(params);

                } else {
                    params.height = params.width;
                    ivIcon.setLayoutParams(params);
                }
            } else {
                params.height = params.width;
                ivIcon.setLayoutParams(params);
            }


            if (data.images().size() > 0) {

                RoundedCorners roundedCorners = new RoundedCorners(10);
                RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(params.width, params.height);
                options.placeholder(R.drawable.default_work);
                Glide.with(mContext).load(data.images().get(0)).apply(options).into(ivIcon);

            } else {
                ivIcon.setImageResource(R.drawable.meinv);
            }


            tvName.setText(data.getUsernickname());
            tvContent.setText(data.getWorkstitle());
            tvNum.setText(data.getWorkspraisenum());

            if (data.getWorkifpraise() != null && data.getWorkifpraise().equals("1")) {
                iv_praise.setImageResource(R.drawable.dianzan1);
            } else {
                iv_praise.setImageResource(R.drawable.dianzan);
            }
            ImageViewUtil.loadCircleImage(data.getUsericon(), ivUserIcon, mContext);


        }


    }

    class PersonHeaderHolder extends BaseViewHolder {
        @BindView(R.id.tagcontainerLayout2)
        TagContainerLayout tagcontainerLayout2;
        @BindView(R.id.l_yincang_bg)
        LinearLayout l_yincang_bg;
        @BindView(R.id.r_bg)
        RelativeLayout r_bg;
        @BindView(R.id.iv_icon)
        ImageView ivIcon;
        @BindView(R.id.iv_yuyin)
        ImageView iv_yuyin;
        @BindView(R.id.iv_guanzhu)
        ImageView iv_guanzhu;
        @BindView(R.id.tv_yincang)
        TextView tvYincang;
        @BindView(R.id.re_tag)
        RecyclerView re_tag;
        @BindView(R.id.l_yincnag)
        LinearLayout l_yincnag;
        @BindView(R.id.tv_guan)
        TextView tv_guan;
        @BindView(R.id.tv_yuyue)
        LinearLayout tv_yuyue;
        @BindView(R.id.tv_gengduo)
        TextView tv_gengduo;
        @BindView(R.id.iv_yincang)
        ImageView ivYincang;
        @BindView(R.id.iv_vip)
        ImageView ivVip;
        @BindView(R.id.l_icon)
        LinearLayout lIcon;
        @BindView(R.id.tv_store_name)
        TextView tv_store_name;
        @BindView(R.id.tv_phone)
        TextView tv_phone;
        @BindView(R.id.tv_email)
        TextView tv_email;
        @BindView(R.id.tv_address)
        TextView tv_address;
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_rank)
        TextView tvRank;
        @BindView(R.id.tv_detail)
        TextView tv_detail;

        @BindView(R.id.tv_brief)
        TextView tvBrief;
        @BindView(R.id.btn_detail)
        ImageButton btnDetail;

        int tvWidth;

        public PersonHeaderHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        //需要截取的位置
        public int subInex(Paint paint, String str) {
            int iRet = 0;
            int j = 0;
            if (str != null && str.length() > 0) {
                int len = str.length();
                float[] widths = new float[len];
                paint.getTextWidths(str, widths);
                for (j = 0; j < len; j++) {
                    iRet += (int) Math.ceil(widths[j]);
                    if (iRet > (tvWidth * 3 - tvWidth / 2)) {
                        break;
                    }
                }
            }
            return j;
        }

        public int getTextWidth(Paint paint, String str) {
            int iRet = 0;
            if (str != null && str.length() > 0) {
                int len = str.length();
                float[] widths = new float[len];
                paint.getTextWidths(str, widths);
                for (int j = 0; j < len; j++) {
                    iRet += (int) Math.ceil(widths[j]);
                }
            }
            return iRet;
        }

        public void setData() {

            UserBean userBean = App.getInstance().getAccount();

            re_tag.setLayoutManager(new GridLayoutManager(mContext,5));


            if(tagAdapter==null){
                tagAdapter= new TagAdapter(mContext);

            }
            tagAdapter.getData().clear();
            tagAdapter.getData().addAll(tag);
            re_tag.setAdapter(tagAdapter);
            ImageViewUtil.loadCircleImage(userBean.getUsericon(), ivIcon, mContext);
            if ( userBean.getUsercompany()!= null) {

                tv_store_name.setText(userBean.getUsercompany());


            } else {
                tv_store_name.setText("");

            }


            tvName.setText(userBean.getUsernickname());
            tvRank.setText(userBean.getUserrank());
            tv_phone.setText("Tel:" + userBean.getUsertel());
            tv_email.setText("Email:" + userBean.getUseremail());
            tv_address.setText("Address:" + userBean.getUseraddress());
//            tvBrief.setText();

            if (userBean.getUsercertificated().equals("1")) {
                ivVip.setVisibility(View.VISIBLE);
            } else {
                ivVip.setVisibility(View.GONE);
            }
//            if (StringUtils.isEmpty(userBean.getUserbrief())) {
//                tvBrief.setText("");
//                tv_detail.setVisibility(View.GONE);
//            } else {
//                tvBrief.setText(StringUtils.split(userBean.getUserbrief(), "\n")[0]);
//                tv_detail.setVisibility(View.VISIBLE);
//            }

            tvBrief.setText(userBean.getUserbrief());
            tagcontainerLayout2.setTags(tag);

            if(ishiden){

                tvYincang.setText("显示全部个人信息");
                ivYincang.setImageResource(R.drawable.jiantou_xia);
            }else {
                tvYincang.setText("隐藏全部个人信息");
                ivYincang.setImageResource(R.drawable.jiantou_shang);
            }
            if(ishiden){
                l_yincang_bg.setVisibility(View.GONE);
            }else {
                l_yincang_bg.setVisibility(View.VISIBLE);
            }


            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) iv_guanzhu.getLayoutParams();
            LinearLayout.LayoutParams yparams = (LinearLayout.LayoutParams) iv_yuyin.getLayoutParams();

            WindowManager m = ((Activity) mContext).getWindowManager();
            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
            params.height = (int) (d.getWidth()*99.0/414.0);
            yparams.height = (int) ((d.getWidth()-ScreenUtil.dp2px(mContext,87))*66.0/414.0);
            iv_guanzhu.setLayoutParams(params);

            iv_yuyin.setLayoutParams(yparams);
//            final Paint paint = new Paint();
//            paint.setTextSize(tvBrief.getTextSize());
//            Rect rect = new Rect();
//            //精确计算文字宽度
//            tvBrief.post(new Runnable() {
//                @Override
//                public void run() {
//                    tvWidth = tvBrief.getWidth();
//                    String test = userBean.getUserbrief().replace("\n","");
//                    int textWidth = getTextWidth(paint, userBean.getUserbrief().replace("\n",""));
//                    if (textWidth > (tvWidth * 3 - tvWidth / 2)) {
//
//                        String text = test.substring(0, subInex(paint, test));
//                        tvBrief.setText(text);
//                        tv_detail.setVisibility(View.VISIBLE);
//                    } else {
//                       tv_detail.setVisibility(View.GONE);
//                        tvBrief.setText(test);
//                    }
//
//                }
//            });


        }

    }

    public interface personListener {
        public void praiseClick(int childPosition);
    }

}
